package com.geekstudy.week5.service;


import com.geekstudy.week5.entity.GeekStudy;
import com.geekstudy.week5.tool.JdbcTool;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class Exercise10PrimitiveJdbcService {



    public List<GeekStudy> queryAll() throws SQLException {
        List<GeekStudy> geekStudyList = new ArrayList<GeekStudy>();

        Connection connection = new JdbcTool().getJdbcConnection();
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery("select * from geek_study");
        for(;resultSet.next();) {
            String id = resultSet.getString("id");
            String name = resultSet.getString("name");
            String nickName = resultSet.getString("nick_name");
            String address = resultSet.getString("address");

            GeekStudy geekStudy = new GeekStudy();
            geekStudy.setId(id);
            geekStudy.setName(name);
            geekStudy.setNickName(nickName);
            geekStudy.setAddress(address);
            geekStudyList.add(geekStudy);
        }
        resultSet.close();
        connection.close();

        return geekStudyList;
    }

    public Map<String, Object> primitive() throws SQLException {
        Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
        Connection connection = new JdbcTool().getJdbcConnection();

        Statement statement = connection.createStatement();
        String deleteSql = "delete from geek_study where id in('p1001', 'p1002')";
        int deleteResult = statement.executeUpdate(deleteSql);
        resultMap.put(deleteSql, deleteResult);

        String insert1 = "insert into geek_study(id, name, nick_name, address) values('p1001', 'name1001', 'nickName1001', 'Primitive2021')";
        int insertResult1 = statement.executeUpdate(insert1);
        resultMap.put(insert1, insertResult1);

        String insert2 = "insert into geek_study(id, name, nick_name, address) values('p1002', 'demo1002', 'Other Demo 1002', 'Primitive2021')";
        int insertResult2 = statement.executeUpdate(insert2);
        resultMap.put(insert2, insertResult2);

        String update1 = "update geek_study set name='nameUpdate1001' where id = 'p1001' ";
        int updateResult1 = statement.executeUpdate(update1);
        resultMap.put(update1, updateResult1);

        statement.close();
        connection.close();

        return resultMap;
    }
}
